package com.ruoyi.web.controller.dwxController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.web.controller.dwxController.domain.User;
import com.ruoyi.web.controller.utils.HttpUtils;
import com.ruoyi.web.domain.*;
import com.ruoyi.web.service.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.List;

/*防止前端调取接口错误
* 修改controller接口地址
* 原本为 /api/index
* */
@RestController
//@RequestMapping("/api/index")
@RequestMapping("/api/old")
public class HTTPJointController {

    @Resource
    private IExecutionRecordService executionRecordService;

    @Resource
    private IExecutionRecordDetailsService executionRecordDetailsService;

    @Resource
    private IExecutionSuccessService executionSuccessService;

    @Resource
    private IReservationFailService reservationFailService;

    @Resource
    private IReservationRecordService reservationRecordService;

    /*
     * 获取到全部的业务号
     * */
    public JSONArray getWorkList1(String userId, String cookie, String orderCount) {
        String url = "https://vcs.vcredit.com/getWorkList1";
        String params = "assignedUserId=" + userId + "&plat=work&folderId=0&orderCount=" + orderCount + "&maxOverPeriodMinInclude=Y&maxOverPeriodMaxInclude=Y&cumOverdueTotalAmountMinInclude=Y&cumOverdueTotalAmountMaxInclude=Y&cumTotalActualAmountMinInclude=Y&cumTotalActualAmountMaxInclude=Y&overdueTotalAmountMinInclude=Y&overdueTotalAmountMaxInclude=Y&overPeriodMinInclude=Y&overPeriodMaxInclude=Y&actualAmountMinInclude=Y&actualAmountMaxInclude=Y&searchMethod=2&pageSize=1000&curPage=1";
        String s = HttpUtils.sendPost(url, params, cookie);
        Map<String, Object> resultMap = JSONObject.parseObject(s).getInnerMap();
        JSONArray jsonArray = (JSONArray) resultMap.get("records");

        /*获取当前账户的订单总数 total*/
        int total = Integer.parseInt(resultMap.get("total") + "");
        if (total / 1000 != 0) {
            for (int i = 0; i < total / 1000; i++) {

                String newParams = "assignedUserId=" + userId + "&plat=work&folderId=0&orderCount=" + orderCount + "&maxOverPeriodMinInclude=Y&maxOverPeriodMaxInclude=Y&cumOverdueTotalAmountMinInclude=Y&cumOverdueTotalAmountMaxInclude=Y&cumTotalActualAmountMinInclude=Y&cumTotalActualAmountMaxInclude=Y&overdueTotalAmountMinInclude=Y&overdueTotalAmountMaxInclude=Y&overPeriodMinInclude=Y&overPeriodMaxInclude=Y&actualAmountMinInclude=Y&actualAmountMaxInclude=Y&searchMethod=2&pageSize=1000&curPage=" + (i + 2);
                String newS = HttpUtils.sendPost(url, newParams, cookie);
                Map<String, Object> newResultMap = JSONObject.parseObject(newS).getInnerMap();
                jsonArray.addAll((JSONArray) newResultMap.get("records"));

            }
        }
        return jsonArray;
    }

    /*
     * 获取用户的userId
     * */
    public String getUseaInfo(String cookie) {
        String url = "https://vcs.vcredit.com/config/websocket";
        String params = "";
        String s = HttpUtils.sendPost(url, params, cookie);
        Map<String, Object> resultMap = JSONObject.parseObject(s).getInnerMap();
        return resultMap.get("userId") + "";
    }

    /*
     * 根据业务号码获取到银行卡信息
     * */
    public JSONObject getAccountNo(String params, String cookie) {
        String url = "https://vcs.vcredit.com/calltask/record/getAccountNo";
        String s = HttpUtils.sendPost(url, params, cookie);
        JSONObject resultMap = JSONObject.parseObject(s);

        return resultMap;
    }

    /*
     * 扣款接口
     * */
    public JSONObject handelDeduct(String Bid, String Amount, String BankCardNo, String cookie) {
        String url = "https://vcs.vcredit.com/calltask/record/handelDeduct";

        /*扣款金额*/
//        String Amount = "100";
        /*业务id*/
//        String Bid = "25020845";
        /*银行卡号*/
//        String BankCardNo = "***************2310";

        StringBuffer params = new StringBuffer();
        params.append("Amount=").append(Amount).append("&").append(Bid).append("&BankCardNo=").append(BankCardNo);
        String s = HttpUtils.sendPost(url, new String(params), cookie);
        JSONObject resultMap = JSONObject.parseObject(s);
        return resultMap;

    }

    /*
     * 根据业务Id 查询扣款执行结果
     * 只获取时间最近的一条
     * */
    public JSONObject checkExecute(String businessId, String cookie) {
        String url = "https://vcs.vcredit.com/calltask/record/sdkkjllist";
        String params = "businessId=" + businessId + "&pageSize=3&curPage=1";
        String s = HttpUtils.sendPost(url, params, cookie);
        JSONObject resultMap = JSONObject.parseObject(s);

        return resultMap;
    }

    /*
     * 获取当前用户的预约扣款订单信息
     * */
    public JSONObject getReservationInfo(String busId, String cookie) {
        String url = "https://vcs.vcredit.com/work_excel/getGuihuKkRecordsInfo";
        String params = "busId=" + busId + "&pageSize=10&curPage=1";
        String s = HttpUtils.sendPost(url, params, cookie);
        JSONObject resultMap = JSONObject.parseObject(s);
        return resultMap;
    }

    /*
     * 预约接口
     * */
    public String advancePaymente(String cookie, HashMap<String, Object> responeMap) {
        String url = "https://vcs.vcredit.com/work_excel/advancePaymente";
        String s = HttpUtils.sendPostForJson(url, cookie, responeMap);
        JSONObject resultMap = JSONObject.parseObject(s);
        String msg = resultMap.get("msg") + "";
        return msg;
    }

    /*
     * 获取当前月份剩余多少天
     * */
    public ArrayList<String> monthEndNum() {

        String time1 = " 11:20:00";
        String time2 = " 16:30:00";
        String time3 = " 18:30:00";
        ArrayList<String> timeList = new ArrayList<>();
        LocalDate now = LocalDate.now();
        LocalDate endOfMonth = now.withDayOfMonth(now.getMonth().length(now.isLeapYear()));
        long remainingDays = now.until(endOfMonth, ChronoUnit.DAYS);

        List<LocalDate> remainingDates = new ArrayList<>();
        for (int i = 1; i <= remainingDays; i++) {
            remainingDates.add(now.plusDays(i));
        }

        for (LocalDate date : remainingDates) {
            timeList.add(date + time1);
            timeList.add(date + time2);
            timeList.add(date + time3);
        }
        return timeList;
    }

    /*添加备注请求*/
    public String postNotes(HashMap<String, Object> responeMap,String cookie){
        String url = "https://vcs.vcredit.com/csr/insert";
        String s = HttpUtils.sendPostForJson(url, cookie, responeMap);
        JSONObject resultMap = JSONObject.parseObject(s);
        String msg = resultMap.get("msg") + "";
        return msg;
    }

    // 获取当前订单的用户联系方式
    public String getUserPhone(String busId,String cookie){
        String url = "https://vcs.vcredit.com/work_excel/getMyInformationInfo";
        HashMap<String,Object> responeMap = new HashMap<>();
        responeMap.put("busId",busId);
        responeMap.put("pageSize","100");
        responeMap.put("curPage","1");
        responeMap.put("sortName","");
        responeMap.put("sortOrder","");
        String s = HttpUtils.sendPost(url, cookie, responeMap);
        JSONObject resultMap = JSONObject.parseObject(s);

        JSONArray jsonArray = (JSONArray) resultMap.get("records");
        if (Objects.isNull(jsonArray) || jsonArray.size() == 0){
            return null;
        }
        JSONObject info = (JSONObject) jsonArray.get(0);
        if (null != info.get("contactInfo") && !"".equals(info.get("contactInfo"))){
            return String.valueOf(info.get("contactInfo"));
        }else if (null != info.get("encPhone") && !"".equals(info.get("encPhone"))){
            return String.valueOf(info.get("encPhone"));
        }else {
            return null;
        }

    }


    @RequestMapping("/deductionMain")
    public AjaxResult deductionMain(String cookie, String Amount) {

        AjaxResult ajaxResult = new AjaxResult();

        if (!Amount.matches("^[0-9]*$")) {
            ajaxResult.put("code", "500");
            ajaxResult.put("msg", "请输入正确的金额！");
            return ajaxResult;
        }

        if (Amount == null || Amount.equals("")) {
            Amount = "100";
        }

        //获取当前登录用户 ---> 自动化程序登录用户

        String loginName = ShiroUtils.getSysUser().getLoginName();

        //清空表
        executionRecordDetailsService.truncateTable(loginName);


        ExecutionRecord executionRecord = new ExecutionRecord();
        /*成功条数*/
        long successTotal = 0;
        /*失败条数*/
        long failTotal = 0;
        //执行列表
        JSONArray workList1 = null;
        try {

            String userId = this.getUseaInfo(cookie);
            if (!userId.equals("")) {
                //获取第三方执行任务列表
                workList1 = this.getWorkList1(userId, cookie, "");
            } else {
                ajaxResult.put("code", "500");
                ajaxResult.put("msg", "获取用户列表数据失败，请联系管理员！");
                return ajaxResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", "500");
            ajaxResult.put("msg", "获取用户列表数据失败，请联系管理员！");
            return ajaxResult;
        }
        //当执行任务列表不为null时
        if (workList1 != null) {
            System.out.println("此账号一共查询到" + workList1.size() + "条数据");
            System.out.println("本次扣款金额为:" + Amount + "元");
            /*执行任务列表总条数*/
            long total = workList1.size();
            executionRecord.setTotal(total);
            //保存执行记录
            executionRecordService.insertExecutionRecord(executionRecord);

            for (Object item : workList1) {
                //记录明细表
                ExecutionRecordDetails executionRecordDetails = new ExecutionRecordDetails();
                //任务对象
                JSONObject obj = (JSONObject) item;
                //业务id
                String bid = "bid=" + obj.get("businessId");
                executionRecordDetails.setBusinessId(Long.parseLong(obj.get("businessId") + ""));
                //用户名称
                executionRecordDetails.setUserName(obj.get("custName") + "");
                //批次
                executionRecordDetails.setBatch(executionRecord.getId());
                //扣款卡号
                JSONObject accountNo = null;
                try {
                    //获取银行卡对象
                    accountNo = this.getAccountNo(bid, cookie);
                } catch (Exception e) {
                    ajaxResult.put("code", "500");
                    ajaxResult.put("msg", "获取用户银行卡数据失败，请联系管理员！");
                    e.printStackTrace();
                }
                if (accountNo != null) {
                    //获取卡号集合
                    JSONArray jsonArray = (JSONArray) accountNo.get("Content");
                    try {
                        if (jsonArray != null) {
                            //获取第一个卡号对象
                            JSONObject contentMap = (JSONObject) jsonArray.get(0);

                            /*获取银行卡卡号* */
                            String cardNo = contentMap.get("cardNo") + "";
                            //当卡号不为空时执行扣款操作，反之不记录成功并认为它是错误的
                            if (cardNo != "") {
                                try {
                                    //扣款操作
                                    JSONObject jsonObject = this.handelDeduct(bid, Amount, cardNo, cookie);
                                    //扣款返回的信息
                                    String msg = jsonObject.get("msg") + "";
                                    System.out.println("业务号：" + obj.get("businessId") + "，提示信息：" + msg);
                                    //当为true时记录成功
                                    if (msg.equals("true")) {
                                        successTotal++;
                                        executionRecordDetailsService.insertExecutionRecordDetails(executionRecordDetails);
                                    } else {
                                        failTotal++;
                                    }
                                } catch (Exception e) {
                                    ajaxResult.put("code", "500");
                                    ajaxResult.put("msg", "扣款失败，请联系管理员！");
                                    e.printStackTrace();
                                }
                            }
                        } else {
                            System.out.println("银行卡信息为空：" + bid);
                        }
                    } catch (Exception e) {
                        System.out.println("银行卡信息为空：" + bid);
                    }
                }
            }
            /*失败条数*/
            executionRecord.setFailTotal(failTotal);
            /*成功条数*/
            executionRecord.setSuccessTotal(successTotal);
            //更新执行记录 总的成功/失败条数
            executionRecordService.updateExecutionRecord(executionRecord);
            ajaxResult.put("code", "200");
            ajaxResult.put("msg", "批量申请成功，共计" + total + "条，申请成功" + successTotal + "条,申请失败" + failTotal + "条。");
            System.out.println("批量处理成功，共计" + total + "条，申请成功" + successTotal + "条,申请失败" + failTotal + "条。");
            return ajaxResult;
        } else {
            ajaxResult.put("code", "200");
            ajaxResult.put("msg", "获取任务数据为空，请核实是否存在任务数据！");
            return ajaxResult;
        }
    }

    @RequestMapping("/screen")
    public AjaxResult screen(String cookie) {

        AjaxResult ajaxResult = new AjaxResult();

        ExecutionRecord executionRecord = new ExecutionRecord();

        /*获取到当前登录用户 ---> 自动化程序登录用户*/
        String loginName = ShiroUtils.getSysUser().getLoginName();

        //扣款成功条数
        long deductionSutotal = 0L;
        //扣款失败条数
        long deductionFautotal = 0L;

        long id = 0L;

        try {
            //清空当前表中的所有数据
//            executionSuccessService.truncateTable(loginName);

            //查询出所有的申请成功列表
            ExecutionRecordDetails executionRecordDetail = new ExecutionRecordDetails();
            executionRecordDetail.setCreateBy(loginName);
            List<ExecutionRecordDetails> executionRecordDetails = executionRecordDetailsService.selectExecutionRecordDetailsList(executionRecordDetail);

            if (executionRecordDetails.size() != 0) {
                //循环遍历每一条数据
                for (int i = 0; i < executionRecordDetails.size(); i++) {

                    id = executionRecordDetails.get(0).getBatch();

                    if (executionRecordDetails.get(i).getBusinessId() != null) {

                        ExecutionSuccess executionSuccess = new ExecutionSuccess();

                        JSONObject jsonObject = this.checkExecute(executionRecordDetails.get(i).getBusinessId() + "", cookie);

                        String rspCode = (String) jsonObject.get("rspCode") + "";
                        if (!rspCode.equals("500")) {
                            //获取扣款信息列表
                            JSONArray jsonArray = (JSONArray) jsonObject.get("records");

                            /* 获取当前订单号所有的扣款记录 */
                            for (int x = 0; x < jsonArray.size(); x++) {

                                //获取前三个扣款对象
                                JSONObject contentMap = (JSONObject) jsonArray.get(x);
                                /*获取扣款结果* */
                                String result = contentMap.get("result") + "";
                                /*获取结果说明* */
                                String resultDesc = contentMap.get("resultDesc") + "";
                                System.out.println("业务号：" + executionRecordDetails.get(i).getBusinessId() + "，扣款结果：" + result + "，扣款说明：" + resultDesc);
                                if (!result.equals("扣款失败")) {

                                    /*获取发送时间* */
                                    String cardNo = contentMap.get("sendTime") + "";
                                    /*获取扣款金额* */
                                    String amount = contentMap.get("amount") + "";

                                    /*获取扣款类型*/
                                    //String deductSourceOrigin = contentMap.get("deductSourceOrigin") + "";

                                    executionSuccess.setBusinessId(executionRecordDetails.get(i).getBusinessId());
                                    executionSuccess.setUserName(executionRecordDetails.get(i).getUserName());
                                    executionSuccess.setSendTime(cardNo);
                                    executionSuccess.setAmount(amount);
                                    executionSuccess.setResult(result);
                                    executionSuccess.setResultDesc(resultDesc);

                                    deductionSutotal++;
                                    executionSuccessService.insertExecutionSuccess(executionSuccess);
                                } else {
                                    deductionFautotal++;
                                }
                            }
                            System.out.println("--------------");
                        }
                    }
                }

                /*
                 *更改主表中的扣款成功条数和失败次数
                 * */
                executionRecord.setId(id);
//                executionRecord.setDeductionFautotal(deductionFautotal);
                executionRecord.setDeductionSutotal(deductionSutotal);

                if (id != 0l) {
                    executionRecordService.updateExecutionRecord(executionRecord);
                }

            } else {
                ajaxResult.put("code", "200");
                ajaxResult.put("msg", "申请成功数据列表为空，请核实列表数据！");
                System.out.println("运行结束");
                return ajaxResult;
            }

            ajaxResult.put("code", "200");
            ajaxResult.put("msg", "查询成功，共计" + executionRecordDetails.size() + "条，扣款成功" + deductionSutotal + "条,扣款失败" + deductionFautotal + "条。");
            System.out.println("查询成功，共计" + executionRecordDetails.size() + "条，扣款成功" + deductionSutotal + "条,扣款失败" + deductionFautotal + "条。");
            return ajaxResult;
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", "500");
            ajaxResult.put("msg", "获取用户列表数据失败，请联系管理员！");
            System.out.println("运行结束");
            return ajaxResult;
        }
    }

    @RequestMapping("/reservation")
    public AjaxResult reservation(Integer Amount, String cookie) {

        int amount = 0;
        /*获取金额*/
        try {
            amount = Integer.parseInt(Amount + "");
        } catch (Exception e) {
            e.printStackTrace();

        }

        /*返回集合*/
        AjaxResult ajaxResult = new AjaxResult();

        /*查询用户集合*/
        JSONArray workList1 = new JSONArray();

        /*预约总览表*/
        ReservationRecord reservationRecord = new ReservationRecord();
        reservationRecord.setCreateBy(ShiroUtils.getSysUser().getLoginName());

        /*内含笔数集合*/
        String[] orderCount = new String[]{"1", "2"};

        /*成功总数*/
        long successTotal = 0;

        /*失败总数*/
        long failTotal = 0;

        /*本月时间集合*/
        ArrayList<String> times = this.monthEndNum();

        /*获取需要预约用户的数据*/
        try {
            String userId = this.getUseaInfo(cookie);

            if (!userId.equals("")) {
                /*查询内含笔数量为1或2 的订单*/
                for (int i = 0; i < orderCount.length; i++) {
                    //获取第三方执行任务列表
                    workList1.addAll(this.getWorkList1(userId, cookie, orderCount[i]));
                }

            } else {
                ajaxResult.put("code", "500");
                ajaxResult.put("msg", "获取用户列表数据失败，请联系管理员！");
                return ajaxResult;
            }

        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", "500");
            ajaxResult.put("msg", "获取用户列表数据失败，请联系管理员！");
            System.out.println("运行结束");
            return ajaxResult;
        }

        if (workList1 != null) {

            /*向记录表中插入总条数*/
            reservationRecord.setReservationNum((long) workList1.size());

            /*如果集合不为null的*/
            System.out.println("此账号一共查询到" + workList1.size() + "条数据");
            for (Object item : workList1) {
                JSONObject obj = (JSONObject) item;
                //业务号
                String busId = String.valueOf(obj.get("businessId"));
                String taskId = String.valueOf(obj.get("taskId"));

                /*获取预约所需要的数据*/
                JSONObject reservationInfo = getReservationInfo(busId, cookie);

                JSONArray records = (JSONArray) reservationInfo.get("records");

                /*存放预约所需要的全部数据*/
                HashMap<String, Object> paramsMap = new HashMap<>();
                /*组装预约的申请的用户订单号和订单金额 集合*/
                List<HashMap<String, Object>> advancePaymenteFornVo = new ArrayList<>();

                if (records != null) {
                    records.forEach(bean -> {
                        JSONObject rebean = (JSONObject) bean;
                        HashMap<String, Object> advance = new HashMap<>();
                        advance.put("advancePaymenteAmount", rebean.get("supportAmount") + "");
                        advance.put("advancePaymenteBusinessId", rebean.get("businessId") + "");
                        advance.put("advancePaymenteOrderAmount", rebean.get("overdueTotalAmount") + "");
                        advancePaymenteFornVo.add(advance);
                    });
                    if (records != null) {
                        for (int i = 0; i < records.size(); i++) {
                            JSONObject rebean = (JSONObject) records.get(i);
                            HashMap<String, Object> advance = new HashMap<>();
                            if (i == 0) {
                                if (Double.parseDouble(rebean.get("supportAmount") + "") <= amount) {
                                    advance.put("advancePaymenteAmount", rebean.get("supportAmount") + "");
                                    advance.put("advancePaymenteBusinessId", rebean.get("businessId") + "");
                                    advance.put("advancePaymenteOrderAmount", rebean.get("overdueTotalAmount") + "");
                                    advancePaymenteFornVo.add(advance);
                                } else {
                                    advance.put("advancePaymenteAmount", Amount);
                                    advance.put("advancePaymenteBusinessId", rebean.get("businessId") + "");
                                    advance.put("advancePaymenteOrderAmount", rebean.get("overdueTotalAmount") + "");
                                    advancePaymenteFornVo.add(advance);
                                }

                            } else {
                                advance.put("advancePaymenteAmount", rebean.get("supportAmount") + "");
                                advance.put("advancePaymenteBusinessId", rebean.get("businessId") + "");
                                advance.put("advancePaymenteOrderAmount", rebean.get("overdueTotalAmount") + "");
                                advancePaymenteFornVo.add(advance);
                            }
                        }
                    }
                }

                paramsMap.put("advancePaymenteFormVo", advancePaymenteFornVo);
                paramsMap.put("taskId", taskId);


                if (times != null) {
                    for (int i = 0; i < times.size(); i++) {
                        try {
                            paramsMap.put("advancePaymentTime", times.get(i));
                            /*提交预约申请*/
                            String s = this.advancePaymente(cookie, paramsMap);
                            if (s.equalsIgnoreCase("ok")) {
                                System.out.println(obj.get("custName") + "订单号：" + busId + "日期:" + paramsMap.get("advancePaymentTime") + "预约成功" + s);
                                successTotal++;
                            } else {
                                System.out.println(obj.get("custName") + "订单号：" + busId + "日期:" + paramsMap.get("advancePaymentTime") + "预约失败" + "失败原因:" + s);
                                failTotal++;
                                /*向预约失败表中插入此条数据*/
                                ReservationFail reservationFail = new ReservationFail();
                                reservationFail.setReservationTime(paramsMap.get("advancePaymentTime") + "");
                                reservationFail.setOrderCount(obj.get("orderCount") + "");
                                reservationFail.setUserName(obj.get("custName") + "");
                                reservationFail.setBusinessId(Long.parseLong(busId));
                                reservationFail.setCreateBy(ShiroUtils.getSysUser().getLoginName());
                                reservationFail.setMsg(s);

                                reservationFailService.insertReservationFail(reservationFail);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println(obj.get("custName") + busId + paramsMap.get("advancePaymentTime") + "预约成功");
                        }
                    }
                }
            }
        }

        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        // 获取当前年份
        int year = calendar.get(Calendar.YEAR);
        // 获取当前月份（注意：月份从0开始，所以需要加1）
        int month = calendar.get(Calendar.MONTH) + 1;
        // 获取当前月份的总天数
        int totalDaysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        // 获取当前日期的天数
        int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
        // 计算剩余天数
        int remainingDays = totalDaysInMonth - currentDay;

        reservationRecord.setSuccessTotal(successTotal);
        reservationRecord.setFailTotal(failTotal);
        reservationRecord.setMouths(year + "-" + month);
        reservationRecord.setDays(remainingDays + "");
        reservationRecordService.insertReservationRecord(reservationRecord);

        ajaxResult.put("code", "200");
        ajaxResult.put("msg", "预约成功，共计" + workList1.size() + "条，预约成功" + successTotal + "条,扣款失败" + failTotal + "条。");
        System.out.println("预约成功，共计" + workList1.size() + "条，预约成功" + successTotal + "条,扣款失败" + failTotal + "条。");
        return ajaxResult;
    }


    /*导入业务id集合*/
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, @RequestParam("cookie") String cookie, @RequestParam("Amount") String Amount) throws Exception {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ExcelUtil<User> util = new ExcelUtil<User>(User.class);
            List<User> userList = util.importExcel(file.getInputStream());
            if (userList.size() > 0) {

                if (!Amount.matches("^[0-9]*$")) {
                    ajaxResult.put("code", "500");
                    ajaxResult.put("msg", "请输入正确的金额！");
                    return ajaxResult;
                }

                if (Amount == null || Amount.equals("")) {
                    Amount = "100";
                }

                //获取当前登录用户 ---> 自动化程序登录用户

                String loginName = ShiroUtils.getSysUser().getLoginName();

                //清空表
                executionRecordDetailsService.truncateTable(loginName);


                ExecutionRecord executionRecord = new ExecutionRecord();
                /*成功条数*/
                long successTotal = 0;
                /*失败条数*/
                long failTotal = 0;
                //执行列表
                JSONArray workList1 = null;
                try {

                    String userId = this.getUseaInfo(cookie);
                    if (!userId.equals("")) {
                        //获取第三方执行任务列表
                        workList1 = JSONArray.parseArray(JSON.toJSONString(userList));
                    } else {
                        ajaxResult.put("code", "500");
                        ajaxResult.put("msg", "获取用户列表数据失败，请联系管理员！");
                        return ajaxResult;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ajaxResult.put("code", "500");
                    ajaxResult.put("msg", "获取用户列表数据失败，请联系管理员！");
                    return ajaxResult;
                }
                //当执行任务列表不为null时
                if (workList1 != null) {
                    System.out.println("此账号一共查询到" + workList1.size() + "条数据");
                    System.out.println("本次扣款金额为:" + Amount + "元");
                    /*执行任务列表总条数*/
                    long total = workList1.size();
                    executionRecord.setTotal(total);
                    //保存执行记录
                    executionRecordService.insertExecutionRecord(executionRecord);

                    for (Object item : workList1) {
                        //记录明细表
                        ExecutionRecordDetails executionRecordDetails = new ExecutionRecordDetails();
                        //任务对象
                        JSONObject obj = (JSONObject) item;
                        //业务id
                        String bid = "bid=" + obj.get("businessId");
                        executionRecordDetails.setBusinessId(Long.parseLong(obj.get("businessId") + ""));
                        //用户名称
                        executionRecordDetails.setUserName(obj.get("custName") != null ? obj.get("custName") + "" : "表格导入,暂无用户名称");
                        //批次
                        executionRecordDetails.setBatch(executionRecord.getId());
                        //扣款卡号
                        JSONObject accountNo = null;
                        try {
                            //获取银行卡对象
                            accountNo = this.getAccountNo(bid, cookie);
                        } catch (Exception e) {
                            ajaxResult.put("code", "500");
                            ajaxResult.put("msg", "获取用户银行卡数据失败，请联系管理员！");
                            e.printStackTrace();
                        }
                        if (accountNo != null) {
                            //获取卡号集合
                            JSONArray jsonArray = (JSONArray) accountNo.get("Content");
                            try {
                                if (jsonArray != null) {
                                    //获取第一个卡号对象
                                    JSONObject contentMap = (JSONObject) jsonArray.get(0);

                                    /*获取银行卡卡号* */
                                    String cardNo = contentMap.get("cardNo") + "";
                                    //当卡号不为空时执行扣款操作，反之不记录成功并认为它是错误的
                                    if (cardNo != "") {
                                        try {
                                            //扣款操作
                                            JSONObject jsonObject = this.handelDeduct(bid, Amount, cardNo, cookie);
                                            //扣款返回的信息
                                            String msg = jsonObject.get("msg") + "";
                                            System.out.println("业务号：" + obj.get("businessId") + "，提示信息：" + msg);
                                            //当为true时记录成功
                                            if (msg.equals("true")) {
                                                successTotal++;
                                                executionRecordDetailsService.insertExecutionRecordDetails(executionRecordDetails);
                                            } else {
                                                failTotal++;
                                            }
                                        } catch (Exception e) {
                                            ajaxResult.put("code", "500");
                                            ajaxResult.put("msg", "扣款失败，请联系管理员！");
                                            e.printStackTrace();
                                        }
                                    }
                                } else {
                                    System.out.println("银行卡信息为空：" + bid);
                                }
                            } catch (Exception e) {
                                System.out.println("银行卡信息为空：" + bid);
                            }
                        }
                    }
                    /*失败条数*/
                    executionRecord.setFailTotal(failTotal);
                    /*成功条数*/
                    executionRecord.setSuccessTotal(successTotal);
                    //更新执行记录 总的成功/失败条数
                    executionRecordService.updateExecutionRecord(executionRecord);
                    ajaxResult.put("code", "200");
                    ajaxResult.put("msg", "批量申请成功，共计" + total + "条，申请成功" + successTotal + "条,申请失败" + failTotal + "条。");
                    System.out.println("批量处理成功，共计" + total + "条，申请成功" + successTotal + "条,申请失败" + failTotal + "条。");
                    return ajaxResult;
                }

            } else {
                ajaxResult.put("data", null);
                ajaxResult.put("code", 500);
                ajaxResult.put("msg", "导入数据条数为0,请重新导入");
            }

        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("data", null);
            ajaxResult.put("code", 500);
            ajaxResult.put("msg", "导入失败,请重新导入");
        }
        return ajaxResult;
    }


    /* 客户订单添加备注 */
    @PostMapping("/addNotes")
    @ResponseBody
    public AjaxResult addNotes(String cookie){

        AjaxResult ajaxResult = new AjaxResult();

        JSONArray workList1 = null;

        int successtotal = 0;

        // 获取用户列表
        try {
            String userId = this.getUseaInfo(cookie);
            if (!userId.equals("")) {
                //获取第三方执行任务列表
                workList1 = this.getWorkList1(userId, cookie, "");
            } else {
                ajaxResult.put("code", "500");
                ajaxResult.put("msg", "获取用户列表数据失败，请联系管理员！");
                return ajaxResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", "500");
            ajaxResult.put("msg", "获取用户列表数据失败，请联系管理员！");
            return ajaxResult;
        }

        if (null != workList1){
            System.out.println("此账号一共查询到" + workList1.size() + "条数据");

            for (int i = 0; i < workList1.size(); i++) {

                JSONObject obj = (JSONObject) workList1.get(i);

                // 获取当前订单的用户联系方式
                String phonenum = this.getUserPhone(String.valueOf(obj.get("businessId")), cookie);

                if (null != phonenum && !"".equals(phonenum)){

                    HashMap<String,Object> requestmap = new HashMap<>();
                    requestmap.put("busId",String.valueOf(obj.get("businessId")));
                    String memo = "客" + phonenum + " 主单业务号已发短信";
                    requestmap.put("memo",memo);
                    requestmap.put("taskId",String.valueOf(obj.get("taskId")));
                    requestmap.put("type","1");

                    // 发送添加备注请求
                    String s = this.postNotes(requestmap, cookie);
                    if (!StringUtil.isNotEmpty(s) || "".equals(s)){
                        System.out.println("当前订单用户businessId:" + obj.get("businessId") + s);
                    }else{
                        System.out.println("当前订单用户businessId:" + obj.get("businessId") + (("ok".equals(s)) ? "留言成功" : s) + memo );
                        successtotal ++;
                    }

                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }else{
                    System.out.println("当前订单用户businessId:" + obj.get("businessId") + "手机号码获取失败,请联系管理员");
                }
            }

            ajaxResult.put("code", "200");
            ajaxResult.put("msg", "共" + workList1.size() + "条,成功留言" + successtotal + "条");
        }else{
            System.out.println("此账号一共查询到0条数据,请联系管理员");
        }

        System.out.println("当前订单业务已处理完毕");
        /*获取到所有客户结合*/
        return ajaxResult;
    }
}